<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color: red;
    }
    #news .router-link-exact-active{
      background-color: rgb(163, 211, 197);
    }
  </style>
</head>
<body>
  <div id="app">
    <!-- 视图上定义 router-view组件 作为路由组件出口 
      router-view定义在哪里，路由组件就在哪里渲染 -->
      <router-link tag="button" to="/home">首页</router-link>
      <router-link tag="button" to="/news">新闻页</router-link>
      <router-link tag="button" to="/about">关于我们页</router-link>
      <hr>
      <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 1 定义路由组件的config对象
    const Home = {
      template: `
        <div>
          <h1>我是home</h1>  
        </div>
      `,
      mounted(){
        console.log(this.$route);
      }
    }
    const News = {
      template: `
        <div id="news">
          <h1>我是新闻</h1>  
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h1>我是关于我们</h1>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h1>我是登录页</h1>  
          <button @click="doLogin">点击登陆</button>
        </div>
      `,
      methods: {
        doLogin(){
          setTimeout(() => {
            const token = 'ftr56tyj7uk8l9io0';
            localStorage.setItem('token', token);
            // 调回到首页
            this.$router.replace('/home')
          }, 1000)
        }
      }
    }
    const routes = [
      // 单个路由规则 是对象
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
       
        component: Home
      },
      {
        path: '/news',
        component: News,
      },
      {
        path: '/about',
        component: About
      },
      {
        path: '/login',
        component: Login
      }
    ]
    // 创建路由 实例
    const router = new VueRouter({
    
      // routes 路由规则
      routes
    })
    const isLogin = () => !!localStorage.getItem('token');
    router.beforeEach((to, from, next) => {
      /* 
        首先应该判断 是否去登录或注册页 是的直接放行
        判断用户是否登陆
          判断缓存是否有token
            有 放行 next
            没有 去登录
      */
      
      if(to.path === '/login' || to.path === '/register'){
        next();
      }else{
        if(isLogin()){
          // 登陆了
          next();
        }else{
          // 没有登录
          next('/login')
        }
      }
      
    })
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>
</html>